import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

@SuppressWarnings("serial")
public class NotesPanel extends JPanel {
	public String USER_FUNC = "Notes";
	private Font custFont = new Font("Arial Bold", Font.BOLD, 15);
	
	private JTextArea ta = new JTextArea();
	private JScrollPane sp = new JScrollPane(ta);
	
	public NotesPanel() {
		ta.setFont(custFont);
		setLayout(new BorderLayout());
		loadNotes();
		add(sp);
		add(createButton("Save Notes"), BorderLayout.SOUTH);
	}
	
	private JButton createButton(final String name) {
		JButton button = new JButton(name);
		button.setFont(custFont);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent ae) {
				saveNotes();
			}
		});
		return button;
	}
	
	private void loadNotes() {			
		FileInputStream fstream;
		try {
			fstream = new FileInputStream(new File("FarmersMarketNotes.txt"));
	  		DataInputStream in = new DataInputStream(fstream);
	  		BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line = br.readLine();
			while (line != null) {
				ta.setText(ta.getText() + line + "\n");
				line = br.readLine();
			}
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void saveNotes() {
		PrintWriter output = null;
		try {
			output = new PrintWriter(new FileOutputStream("FarmersMarketNotes.txt"));
			for (String line : ta.getText().split("\\n"))
				output.println(line);
		} catch(FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if(output != null)
				output.close();
		}
	}
}
